<?php


namespace app\controller\admin;


use app\common\OrderStatus;
use app\models\order\OrderDetailModel;
use app\models\order\OrderModel;
use app\models\shop\ShopModel;
use app\models\user\DetailedGreenScoresModel;
use app\services\order\OrderService;
use app\services\user\DetailIntegralService;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use think\facade\Db;

use app\services\user\DetailMoneyService;
use app\services\user\DetailedGreenScoresService;

class OrderController extends BaseAdminController
{
    function setSearch()
    {
        $where = [];
        $userInfo = $this->request->param('user_info', '', 'trim');
        if ($userInfo) {
            $orderIdArr = OrderModel::where('username|user_mobile|address_detail', 'like', '%' . $userInfo . '%')->column('id');
            $where[] = ['id', 'in', $orderIdArr];
        }
        return [
            'eq' => ['order_status'],
            'like' => ['order_sn'],
            'between' => ['create_time'],
            'custom' => $where
        ];
    }

    function setSort()
    {
        return [
            'inviter_name' => 'inviter',
            'level_name' => 'level',
        ];
    }

    /**
     * 获取订单状态
     * @return \think\response\Json
     */
    public function getOrderStatusArr()
    {
        try {
            $list = OrderService::getOrderStatusArr();
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    public function getOrderList()
    {
        try {
            $orderSn = $this->request->param('order_sn', '', 'trim');
            $user_info = $this->request->param('user_info', '', 'trim');
            $status = $this->request->param('order_status', 0);
            $create_time = $this->request->param('create_time', '', 'trim');

            $where = [];
            $where[] = ['is_del', '=', 0];
            if ($orderSn) {
                $where[] = ['order_sn', 'like', '%' . $orderSn . '%'];
            }
            if($user_info){
                $where[] = ['username|user_mobile','like',"%{$user_info}%"];
            }

            if ($status) {
                $where[] = ['order_status', '=', $status];
            }

            if($create_time && !empty($create_time['0'])){
                $where[] = ['create_time', 'between', [strtotime($create_time['0']), strtotime($create_time['1'])]];
            }
            $page = $this->page;
            $limit = $this->limit;

            //dump($where);die;
            $list = OrderModel::where($where)
                ->order('id', 'desc')
                ->paginate(['list_rows' => $limit, 'page' => $page])
                ->toArray();
            foreach ($list['data'] as &$v) {
                if ($v['shop_id']) {
                    $shopInfo = ShopModel::find($v['shop_id']);
                    $v['shop_name'] = $shopInfo['shop_name'];
                } else {
                    $v['shop_name'] = '';
                }
                $v['order_status_txt'] = OrderService::getOrderStatusAttr($v['order_status']);
                $v['after_sales_time'] = date('Y-m-d H:i',$v['after_sales_time']);
            }
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    public function getOrderDetail()
    {
        Db::startTrans();
        try {
            $id = $this->request->param('id', 0);
            $orderInfo = OrderModel::find($id);
            if (!$orderInfo) {
                throw new \Exception('订单不存在');
            }
            $orderDetail = OrderDetailModel::where('order_sn', $orderInfo['order_sn'])->select()->toArray();
            $orderInfo['detail'] = $orderDetail;
            Db::commit();
            return $this->success($orderDetail);
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }

    public function exportOrderExcel()
    {
        try {
            $status = $this->request->param('order_status', 0);
            $sellPhone = $this->request->param('sell_phone', '', 'trim');
            $buyPhone = $this->request->param('buy_phone', '', 'trim');
            $orderSn = $this->request->param('order_sn', '', 'trim');
            $startTime = $this->request->param('start_time', '');
            $endTime = $this->request->param('end_time', '');
            $where = [];
            $where[] = ['is_del', '=', 0];
            if ($status) {
                $where[] = ['order_status', '=', $status];
            }
            if ($sellPhone) {
                $uid = Db::name('user')->where('mobile', $sellPhone)->value('id');
                $where[] = ['user_id', '=', $uid];
            }
            if ($buyPhone) {
                $uid = Db::name('user')->where('mobile', $buyPhone)->value('id');
                $where[] = ['buy_user_id', '=', $uid];
            }
            if ($orderSn) {
                $where[] = ['order_sn', 'like', '%' . $orderSn . '%'];
            }
            if ($startTime && $endTime) {
                $where[] = ['create_time', 'between', [$startTime, $endTime]];
            }
            $list = OrderModel::where($where)
                ->order('id', 'desc')
                ->select()
                ->toArray();
            $spreadsheet = new Spreadsheet();
            $worksheet = $spreadsheet->getActiveSheet();
            $worksheet->setCellValue("A1", '订单号');
            $worksheet->setCellValue("B1", '收货人');
            $worksheet->setCellValue("C1", '手机号');
            $worksheet->setCellValue("D1", '收货地址');
            $worksheet->setCellValue("E1", '订单总价');
            $worksheet->setCellValue("F1", '支付时间');
            $worksheet->setCellValue("G1", '状态');
            $worksheet->setCellValue("H1", '备注');
            $worksheet->setCellValue("I1", '商品名称');
            $worksheet->setCellValue("J1", '快递公司');
            $worksheet->setCellValue("K1", '快递单号');
            $i = 2;
            foreach ($list as $v) {
                $orderStatus = OrderStatus::getOrderStatusTxt($v['order_status']);
                $worksheet->setCellValue("A" . $i, $v['order_sn']);
                $worksheet->setCellValue("B" . $i, $v['user_name']);
                $worksheet->setCellValue("C" . $i, $v['user_phone']);
                $worksheet->setCellValue("D" . $i, $v['address_detail']);
                $worksheet->setCellValue("E" . $i, $v['total_price']);
                $worksheet->setCellValue("F" . $i, $v['pay_time']);
                $worksheet->setCellValue("G" . $i, $orderStatus);
                $worksheet->setCellValue("H" . $i, $v['remark']);
                $worksheet->setCellValue("I" . $i, $v['goods_id_str']);
                $i++;
            }
            $writer = new Xlsx($spreadsheet);
            $filename = date("YmdHis") . '发货订单.xlsx';
            $filePrefix = 'static/xlsl/';
            $filePath = $filePrefix . $filename;
            $fullPath = root_path() . 'public/' . $filePrefix;
            if (file_exists($fullPath . $filename)) {
                return $filePath;
            }
            if (!file_exists($fullPath)) {
                mkdirs($fullPath, 0755);
            }
            $writer->save($fullPath . $filename);
            /* 释放内存 */
            $spreadsheet->disconnectWorksheets();
            unset($objSpreadsheet);

            return $this->success(['file_path' => $filePath]);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    public function sendGoods()
    {
        Db::startTrans();
        try {
            $id = $this->request->param('id', 0);
            $delivery_express = $this->request->param('delivery_express');
            if (!$delivery_express) {
                throw new \Exception('请填写快递公司');
            }
            $delivery_no = $this->request->param('delivery_no');
            if (!$delivery_no) {
                throw new \Exception('请填写快递单号');
            }
            $orderInfo = OrderModel::find($id);
            if (!$orderInfo) {
                throw new \Exception('订单不存在');
            }
            if ($orderInfo['order_status'] != 2) {
                throw new \Exception('订单状态错误');
            }
            $orderInfo->order_status = 3;
            $orderInfo->delivery_express = $delivery_express;
            $orderInfo->delivery_no = $delivery_no;
            $orderInfo->delivery_time = time();
            $orderInfo->save();
            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 售后
     * @return void
     */
    public function afterSales()
    {
        Db::startTrans();
        try {
            $id = $this->request->param('id', 0);
            $type = $this->request->param('type');
            $orderInfo = OrderModel::find($id);
            if (!$orderInfo) {
                throw new \Exception('订单不存在');
            }
            if ($orderInfo['order_status'] != 7) {
                throw new \Exception('订单状态错误');
            }
            if($type == 1){
                //同意退款
                if($orderInfo['pay_type'] == 1){
                    //微信支付
                }elseif($orderInfo['pay_type'] == 2){
                    //支付宝
                    $strategy = new AliPay();
                    $service = new PayService();
                    $service->setStrategy($strategy);
                    $service->refund($id, '订单取消');
                }elseif($orderInfo['pay_type'] == 3){
                    //积分加余额
                    //消费积分 余额
                    $type = DetailMoneyService::ORDER_REFUND;
                    DetailMoneyService::create($orderInfo['user_id'],$type,$orderInfo['order_balance'],$orderInfo['order_sn']);

                    $type = DetailIntegralService::RETURN;
                    DetailIntegralService::create($orderInfo['user_id'],$type,$orderInfo['order_integral'],$orderInfo['order_sn']);
                }elseif($orderInfo['pay_type'] == 4){

                    //修改用户余额
                    $type = DetailMoneyService::ORDER_REFUND;
                    DetailMoneyService::create($orderInfo['user_id'],$type,$orderInfo['pay_amount'],$orderInfo['order_sn']);
                }

                //减少用户的绿色积分
                $type = DetailedGreenScoresService::REDEMPTION;
                DetailedGreenScoresService::create($orderInfo['user_id'],$type,$orderInfo['green_scores'],$orderInfo['order_sn']);

                $orderInfo->order_status = 8;
                $orderInfo->refund_amount = $orderInfo->pay_amount;
                $orderInfo->update_time = time();
                $orderInfo->save();
            }else{
                //不同意
                $orderInfo->order_status = $orderInfo->after_sales_status;
                $orderInfo->update_time = time();
                $orderInfo->save();
            }
            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }


}